package org.makabaka.wfwwb.service.Impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.makabaka.wfwwb.common.ServiceException;
import org.makabaka.wfwwb.mapper.UserMapper;
import org.makabaka.wfwwb.pojo.User;
import org.makabaka.wfwwb.service.UserService;
import org.makabaka.wfwwb.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public User login(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        User quser = userMapper.selectOne(queryWrapper);
        if (quser == null) {
            throw new ServiceException("401", "登录失败: 用户名或密码错误");
        }
        if (!user.getPassword().equals(quser.getPassword())) {
            throw new ServiceException("401", "登录失败: 用户名或密码错误");
        }
        quser.setToken(UserUtil.getToken(quser));
        quser.setPassword("");
        return quser;
    }

    @Override
    public int register(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        User quser = userMapper.selectOne(queryWrapper);
        if (quser != null) {
            throw new ServiceException("401", "注册失败: 该用户名已注册");
        }
        if (user.getUsername().length() < 1 || user.getUsername().length() > 32) {
            throw new ServiceException("401", "注册失败: 用户名长度超出限制[1, 32]");
        }
        if (user.getPassword().length() < 1 || user.getPassword().length() > 32) {
            throw new ServiceException("401", "注册失败: 密码长度超出限制[1, 32]");
        }
        int q;
        try {
            q = userMapper.insert(user);
        } catch (Exception e) {
            throw new ServiceException("401", "注册失败: 请联系管理员");
        }
        return q;
    }

    @Override
    public User getUserInfo(String token) {
        String username = (String) JWTUtil.parseToken(token).getPayload("username");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User quser = userMapper.selectOne(queryWrapper);
        quser.setPassword("");
        return quser;
    }


}
